package com.none.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.none.usercenter.common.BaseResponse;
import com.none.usercenter.common.ErrorCode;
import com.none.usercenter.common.ResultUtils;
import com.none.usercenter.excption.BusinessException;
import com.none.usercenter.model.domain.File;
import com.none.usercenter.model.domain.User;
import com.none.usercenter.model.domain.request.ApiResponse;
import com.none.usercenter.model.domain.request.UserLoginRequest;
import com.none.usercenter.model.domain.request.UserRegisterRequest;
import com.none.usercenter.service.FileService;
import com.none.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.none.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.none.usercenter.contant.UserConstant.USER_LOGIN_SATE;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private FileService fileService;


    // 总文件目录
    private final String BASE_UPLOAD_DIR = "file/";
    /**
     * 获取按日期分类的文件夹路径
     */
    private String getDateFolderPath() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFolder = dateFormat.format(new Date());
        return BASE_UPLOAD_DIR + dateFolder + "/";
    }

    /**
     * 创建必要的目录结构
     */
    private void createDirectoriesIfNotExist(String path) throws IOException {
        Path directoryPath = Paths.get(path);
        if (!Files.exists(directoryPath)) {
            Files.createDirectories(directoryPath);
        }
    }


    /**
     * 格式化文件大小
     */
    private String formatFileSize(long size) {
        if (size <= 0) return "0 B";

        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));

        return String.format("%.2f %s", size / Math.pow(1024, digitGroups), units[digitGroups]);
    }

    @PostMapping("/upload")
    public ResponseEntity<Map<String,Object>>  uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("status", "error");
                response.put("message", "上传文件失败");
                return ResponseEntity.badRequest().body(response);
            }

            // 方法1: 直接使用 getSize() 获取文件大小（字节）
            long fileSize = file.getSize();
            // 转换为更友好的格式
            String formattedSize = formatFileSize(fileSize);

            System.out.println("文件大小（字节）: " + fileSize);
            System.out.println("格式化大小: " + formattedSize);

            // 获取按日期分类的文件夹路径
            String dateFolderPath = getDateFolderPath();

            // 创建目录（如果不存在）
            createDirectoriesIfNotExist(dateFolderPath);

            // 生成唯一的文件名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFileName != null && originalFileName.contains(".")) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + fileExtension;
            String uuid = UUID.randomUUID().toString();

            // 保存文件到日期文件夹
            Path filePath = Paths.get(dateFolderPath + fileName);
            Files.copy(file.getInputStream(), filePath);

            //创建人
            User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_SATE);
            String userAccount = currentUser.getUserAccount();

            // 记录文件信息（可选）
            System.out.println("文件保存路径: " + filePath.toAbsolutePath());

            boolean b = fileService.saveFile(uuid, formattedSize, originalFileName, userAccount);
            if (!b) {
                response.put("status", "error");
                response.put("message", "上传失败");
                return ResponseEntity.badRequest().body(response);
            }
            response.put("status", "success");
            response.put("message","上传成功");
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.put("status", "error");
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PostMapping("/queryfile")
    public ResponseEntity<Map<String,Object>>  uploadFile(HttpServletRequest httpServletRequest) throws IOException {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) httpServletRequest.getSession().getAttribute(USER_LOGIN_SATE);
        if (currentUser == null){
            response.put("status", "error");
            response.put("message","查询失败");
            return ResponseEntity.badRequest().body(response);
        }
        String userAccount = currentUser.getUserAccount();
        List<File> fileList = fileService.getFileList(userAccount);
        // 构建响应
        response.put("status", "success");
        response.put("fileList", fileList);
        return  ResponseEntity.ok(response);
    }


    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount,password,checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        long result = userService.userRegister(userAccount, password, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_SATE);
        if (currentUser == null){
           throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/login")
    public BaseResponse<User> userRegister(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null){
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String password = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount,password)){
            return null;
        }
        User dologin = userService.dologin(userAccount, password, request);
        return ResultUtils.success(dologin);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null){
            return null;
        }
        int i = userService.userLginOut(request);
        return ResultUtils.success(i);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username,HttpServletRequest request){
        if (!isAdmin(request)){
           throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> list = userService.list(queryWrapper);
        List<User> collect = list.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request){
        if (!isAdmin(request)){
            return null;
        }
        if(id <= 0){
            return null;
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    private boolean isAdmin(HttpServletRequest request){
        //仅管理员可查询
        User user =(User) request.getSession().getAttribute(USER_LOGIN_SATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }
}